package com.phone580.app;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.WifiManager;

import com.phone580.app.Worker.CompleteCallback;
import com.phone580.app.entity.DownloadInfoEntity;
import com.phone580.app.model.DownloadManagerModel;
import com.phone580.app.receiver.NetworkStatusReceiver;
import com.phone580.app.service.DownloadService;
import com.phone580.app.untilty.CommonUtility;

public class MainApplication extends Application {
	
//	public DownloadCallback callback;
//	private ServiceConnection connection = new ServiceConnection() {
//		
//		@Override
//		public void onServiceDisconnected(ComponentName name) {
//			System.out.println("service disconnected");
//		}
//		
//		@Override
//		public void onServiceConnected(ComponentName name, IBinder service) {
//			System.out.println("service connnected success");
//			callback = (DownloadCallback) service;
//		}
//	};
	
//	private List<DownloadInfoEntity> downloadList = new ArrayList<DownloadInfoEntity>();
	
	private ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
			2, 3, 3, TimeUnit.SECONDS,
			new LinkedBlockingQueue<Runnable>(),
			new ThreadPoolExecutor.DiscardOldestPolicy());
	
	public ThreadPoolExecutor getThreadPool() {
		return this.threadPool;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		registerReceiver();
		restoreDownloadList();
		 if(!CommonUtility.isSDCardAvailable()){
			 File mnt = new File("/mnt");
			 String[] files = mnt.list();
			 for (String file : files) {
				 if (file.toUpperCase().contains("SDCARD") && !"SDCARD".equals(file.toUpperCase())) {
					 CommonData.SDCARD = "/mnt/" + file;
					 break;
				 }
			 }
		 }
		 CommonData.init();
		 File file = new File(CommonData.APP_PATH);
		if (!file.exists()) {
			file.mkdir();
		}
		
//		bindService(new Intent(this, DownloadService.class), connection, BIND_AUTO_CREATE);
		String onlyWIFI = CommonUtility.getStoreValue(this, "only_wifi");
		String notification = CommonUtility.getStoreValue(this, "notification");
		if (onlyWIFI == null) {
			CommonData.ONLY_WIFI = false;
		} else {
			CommonData.ONLY_WIFI = Boolean.valueOf(onlyWIFI);
		}
		if (notification == null) {
			CommonData.Notification = true;
		} else {
			CommonData.Notification = Boolean.valueOf(notification);
		}
		
		AppUpgradeTask task = new AppUpgradeTask(this);
		task.execute();
	}
	
	private Map<Integer, Future<?>> taskTrack = new HashMap<Integer, Future<?>>();
	private List<DownloadInfoEntity> downloadList = new ArrayList<DownloadInfoEntity>();
	
	public List<DownloadInfoEntity> getDownloadList() {
		return downloadList;
	}
	
	public void startDownload(DownloadInfoEntity info) {
		if (!downloadList.contains(info)) {
			downloadList.add(info);
		}
		info.setStatus(Constant.DOWNLOAD_STANDBY);
		if (CommonData.ONLY_WIFI && !CommonUtility.isWiFiActive(this)) {
			info.setStatus(Constant.DOWNLOAD_PAUSE);
			return;
		}
		Future<?> future = threadPool.submit(new Worker(info, new CompleteCallback() {
			
			@Override
			public void complete(DownloadInfoEntity info) {
				downloadList.remove(info);
				DownloadManagerModel model =new DownloadManagerModel(MainApplication.this);
				model.updateStatus(info);
				showNotification(info);
			}

			@Override
			public void stop(DownloadInfoEntity info) {
				System.out.println("----------------------------------------stop");
				DownloadManagerModel model =new DownloadManagerModel(MainApplication.this);
				if (info.getStatus() == Constant.DOWNLOAD_PAUSE) {
					model.updateStatus(info);
				} else if (info.getStatus() == Constant.DOWNLOAD_CANCEL) {
					model.remove(info.getId());
				}
				
			}
		}));
		taskTrack.put(info.hashCode(), future);
	}
	
	public void pauseDownload(DownloadInfoEntity info) {
		info.setStatus(Constant.DOWNLOAD_PAUSE);
		Future<?> future = taskTrack.get(info.hashCode());
		if (future != null) {
			future.cancel(true);
		}
		taskTrack.remove(info.hashCode());
		threadPool.purge();
	}
	
	public void cancelDownload(DownloadInfoEntity info) {
		DownloadManagerModel model = new DownloadManagerModel(this);
		info.setStatus(Constant.DOWNLOAD_CANCEL);
		Future<?> future = taskTrack.get(info.hashCode());
		if (future != null) {
			future.cancel(true);
		}
		taskTrack.remove(info.hashCode());
		threadPool.purge();
		model.remove(info.getId());
		downloadList.remove(info);
		File file = new File(info.getFilePath());
		if (file.exists()) {
			file.delete();
		}
	}
	
	public  void pauseAllDownload() {
		for (DownloadInfoEntity info : downloadList) {
			info.setStatus(Constant.DOWNLOAD_PAUSE);
			Future<?> future = taskTrack.get(info.hashCode());
			if (future != null) {
				future.cancel(true);
			}
			taskTrack.remove(info.hashCode());
			threadPool.purge();
		}
	}
	
	public void saveDownloadList() {
		pauseAllDownload();
		DownloadManagerModel model = new DownloadManagerModel(this);
		model.saveDownloadList(downloadList);
	}
	
	private void restoreDownloadList() {
		DownloadManagerModel model = new DownloadManagerModel(this);
		downloadList.addAll(model.getUnfinish());
	}
	
	private int notifyId = 0;
	private void showNotification(DownloadInfoEntity info) {
		if (!CommonData.Notification) {
			return;
		}
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		String type = "application/vnd.android.package-archive";
		intent.setDataAndType(Uri.fromFile(new File(info.getFilePath())),
				type);
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		PendingIntent contentIntent = PendingIntent.getActivity(
				this, 0, intent, 0);
		Notification notif = new Notification(R.drawable.phone580_icon_small,
				info.getFileName(), 2000);
		notif.flags |= Notification.FLAG_AUTO_CANCEL;
		notif.setLatestEventInfo(this, "下载完成",
				info.getFileName(), contentIntent);
		int id = notifyId++;
		nm.notify(id, notif);
		CommonData.notificationId.put(info.getFileName(), id);
	}
	
	public void cleanAllNotification() {
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nm.cancelAll();
	}
	
	private void registerReceiver() {
		NetworkStatusReceiver receiver = new NetworkStatusReceiver(this);
		IntentFilter filter=new IntentFilter();
		filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		this.registerReceiver(receiver, filter);
	}
	
	@Override
	public void onTerminate() {
//		unbindService(connection);
		this.stopService(new Intent(this, DownloadService.class));
		super.onTerminate();
		
	}
}
